<?php
/**
 * 企业用户登录
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/7/13
 * Time: 16:18
 */
namespace app\wchat\controller;

use app\admin\model\Admin;
use think\App;
use think\Controller;
use think\Request;
use think\Validate;

class Enter extends Controller
{
    public function __construct(App $app = null)
    {
        if(!session('euid') || session('egid') != 6){
            $this->redirect('Login/loginUI');
        }
        parent::__construct($app);

    }

    /**
     * 主页
     * @return mixed
     */
    public function index(){
        return $this->fetch('main');
    }

    /**
     * 任务列表页面
     * @return mixed
     */
    public function listUI(){
        return $this->fetch('list');
    }

    /**
     * 任务单想起页面
     * @return mixed
     */
    public function getDisUI(){

        $id = input('id');
        $info = db('dispatch')->alias('w')->where('w.id',$id)
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username'])
            ->find();
        $info['ticket'] = explode(';',$info['ticket']);
        $info['arge'] = explode(';',$info['arge']);


        return $this->fetch('getDis',['info'=>$info]);
    }

    /**
     * 跟踪页面
     * @return mixed
     */
    public function trackUI(){
        return $this->fetch('track');
    }
    /**
     * 工程师管理页面
     * @return mixed
     */
    public function enginUI(){
        return $this->fetch('engin');
    }

    /**
     * 工程师添加页面
     * @return mixed
     */
    public function enginAddUI(){

        if(request()->isPost()){
            $data = input('post.');

            $check_user = Admin::get(['username'=>$data['username']]);
            if ($check_user) {
                return $result = ['code'=>0,'msg'=>'用户已存在，请重新输入用户名!'];
            }
            $data['pwd'] = input('post.pwd', '', 'md5');
            $data['add_time'] = time();
            $data['ip'] = request()->ip();
            $data['group_id'] = 5;
            $data['a_pid'] = session('euid');
            $data['is_part'] = 1;
            //验证
            $msg = $this->validate($data,'app\admin\validate\Admin');
            if($msg!='true'){
                return json(['code'=>0,'msg'=>$msg]);
            }
            //单独验证密码
            $checkPwd = Validate::make([input('post.pwd')=>'require']);
            if (false === $checkPwd) {
                return json(['code'=>0,'msg'=>'密码不能为空！']);
            }
            //添加
            if (Admin::create($data)) {
                return json(['code'=>1,'msg'=>'添加成功!','url'=>url('listUI')]);
            } else {
                return json(['code'=>0,'msg'=>'添加失败!']);
            }
        }


        $rows = db('jobs')->order('sort')->select();

        $data = [];
        foreach ($rows as $v){
            $data[] = [
                'id'=>$v['id'],
                'value'=>$v['title']
            ];
        }
        $info = [
            'jobs_id'=>'',
            'username'=>'',
            'name'=>'',
            'tel'=>'',
            'email'=>'',
            'good_at'=>'',
            'avatar'=>'',
        ];
        $this->assign('of', 0);
        $this->assign('info',$info);
        $this->assign('data', json_encode($data));

        return $this->fetch('enginAdd');
    }


    public function enginEditUI(){
        if(request()->isPost()){
            $data = input('post.');
            $pwd=input('post.pwd');
            $map[] = ['admin_id','<>',$data['admin_id']];
            $where['admin_id'] = $data['admin_id'];

            if($data['username']){
                $map[] = ['username','=',$data['username']];
                $check_user = Admin::where($map)->find();
                if ($check_user) {
                    return $result = ['code'=>0,'msg'=>'用户已存在，请重新输入用户名!'];
                }
            }
            if ($pwd){
                $data['pwd']=input('post.pwd','','md5');
            }else{
                unset($data['pwd']);
            }
            $msg = $this->validate($data,'app\admin\validate\Admin');
            if($msg!='true'){
                return $result = ['code'=>0,'msg'=>$msg];
            }
            Admin::update($data,$where);

            return $result = ['code'=>1,'msg'=>'修改成功!','url'=>url('listUI')];
        }else{
            $admin = new Admin();
            $info = $admin->getInfo(input('aid'));
            $this->assign('info', $info);
            $this->assign('title',lang('edit').lang('admin'));

            $rows = db('jobs')->order('sort')->select();

            $data = [];
            foreach ($rows as $v){
                $data[] = [
                    'id'=>$v['id'],
                    'value'=>$v['title']
                ];
            }

            $this->assign('of', 1);

            $this->assign('data', json_encode($data));
            return $this->fetch('enginAdd');
        }
    }

    /**
     * 团队页面
     */
    public function teamUI(){
        return $this->fetch('team');
    }

    /**
     * 团队添加
     * @return mixed
     */
    public function teamAddUI(){
        return $this->fetch('teamAdd');
    }


/******************工程师管理**********************/

    /**
     * 工程师列表
     * @param Request $request
     * @return array
     */
    public function eQuery(Request $request){
        $input = $request->param();
        $input['gid'] = 5;
        //$input['apid'] = session('euid');
        $rows = db('admin')->alias('a')->where(function ($query)use($input){
            if(!empty($input['gid']))
                $query->where('a.group_id',$input['gid']);
            /*if(!empty($input['is_part']))
                $query->where('a.is_part',$input['is_part']);*/
            if(!empty($input['aid']))
                $query->where('a.admin_id',$input['aid']);
            if(!empty($input['apid']))
                $query->where('a.a_pid',$input['apid']);
        })
            ->join('auth_group ag','a.group_id=ag.group_id','left')
            ->join('jobs js','js.id=a.jobs_id','left')
            ->field(['a.*,ag.title','js.title as jobs_title'])
            ->select();
        return $result = ['code'=>1,'msg'=>'获取成功!','data'=>$rows,'rel'=>1];
    }

    /**
     * 修改工程师信息
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function eEdit(Request $request)
    {
        $input = $request->param();
        if(empty($input['admin_id'])) return ['code'=>0,'msg'=>'aid参数错误'];
        $count = db('admin')->where([['admin_id','<>',$input['admin_id']],['username','=',$input['username']]])->count();
        if($count)
            return ['code'=>0,'msg'=>'用户名已存在'];
        $count = db('admin')->where([['admin_id','<>',$input['admin_id']],['tel','=',$input['tel']]])->count();
        if($count)
            return ['code'=>0,'msg'=>'手机号码存在'];

        if(!empty($input['pwd'])){
            $input['pwd'] = md5($input['pwd']);
        }
        $row = db('admin')->where('admin_id',$input['admin_id'])->update($input);
        if($row)
            return ['code'=>1,'msg'=>"修改成功"];
        return ['code'=>0,'msg'=>"修改失败"];
    }

    /**
     * 添加工程师
     * @param Request $request
     * @return array
     */
    public function eAdd(Request $request){
        $input = $request->param();
        if(empty($input['pwd'])) return ['code'=>0,'msg'=>"密码不能为空"];

        $count = db('admin')->where('username',$input['username'])->count();
        if($count)
            return ['code'=>0,'msg'=>'用户名已存在'];
        $count = db('admin')->where('tel',$input['tel'])->count();
        if($count)
            return ['code'=>0,'msg'=>'手机号码存在'];

        $input['pwd'] = md5($input['pwd']);
        $input['add_time'] = time();
        $input['ip'] = $request->ip();
        $input['group_id'] = 5;
        $input['a_pid'] = session('euid');
        $input['is_part'] = 1;

        $row = db('admin')->insertGetId($input);
        if($row)
            return ['code'=>1,'msg'=>'添加成功'];
        return ['code'=>0,'msg'=>'添加失败'];
    }


    /**
     * 状态
     * @param Request $request
     */
    public function enable(Request $request){
        $aid = $request->param('aid');
        $is_open = $request->param('isopen');
        $row = db('admin')->where('admin_id='.$aid)->update(['is_open'=>$is_open]);
        if($row)
            return ['code'=>1,'msg'=>'状态修改成功'];
        return ['code'=>0,'msg'=>'状态修改失败'];
    }

    /*********************任务管理***********************/
    public function disQuery(Request $request){
        $input = $request->param();

        $rows = db('dispatch')->alias('w')->order('w.id desc')->where(function ($query)use($input){

            $query->where('w.admin_id',session('euid'));

            if(!empty($input['id'])){
                $query->where('w.id',$input['id']);
            }

            if(!empty($input['fault_id'])){
                $query->where('w.fault_id',$input['fault_id']);
            }
            if(!empty($input['state_id'])){
                $sis = explode(',',$input['state_id']);
                $query->where('w.state_id','in',$sis);
            }

            if(!empty($input['key'])){
                $query->where('w.title|ws.number|w.tel','LIKE','%'.$input['key'].'%');
            }
        })
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username'])
            ->paginate($input['limit'])->toArray();

        return ['code'=>0,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total'],'rel'=>1];
    }

    /**
     * 获取任务
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDis(Request $request){
        $did = $request->param('id');
        $row = db('dispatch')->alias('w')->where('w.id',$did)
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code'])
            ->find();
        $at = db('dispatch_at')->alias('da')->where(['da.is_lead'=>1,'da.dispatch_id'=>$did])->join('admin a','a.admin_id=da.admin_id','left')->field(['da.*','a.username','a.name'])->find();
        $row['lead'] = $at;
        return ['code'=>1,'msg'=>'','data'=>$row];
    }

    /**
     * 接单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function receipt(Request $request)
    {
        $id = $request->param('dis_id');
        if(empty($id)) return ['code'=>0,'msg'=>'id参数错误'];
        $row = db('dispatch')->where('id',$id)->where('admin_id',session('euid'))->update(['state_id'=>21]);
        if($row){

            $info = db('admin')->where('admin_id',session('euid'))->find();
            $input = [];
            $input['icon']        = "/public/static/wx/img/progress-list/t1.png";
            $input['admin_id']    = session('euid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."单位已接单";
            $input['step']        = 1;

            db('dispatch_flow')->insert($input);

            return ['code'=>1,'msg'=>'接单成功'];
        }
        return ['code'=>0,'msg'=>'接单失败'];
    }
    /**
     * 拒单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function refusal(Request $request)
    {
        $id = $request->param('dis_id');
        $val = $request->param('val');
        if(empty($id)) return ['code'=>0,'msg'=>'id参数错误'];
        if(empty($val)) return ['code'=>0,'msg'=>'请输入拒单原因'];
        $row = db('dispatch')->where('id',$id)->where('admin_id',session('euid'))->update(['state_id'=>23,'reason'=>$val]);
        if($row)
            return ['code'=>1,'msg'=>'信息发送成功'];
        return ['code'=>0,'msg'=>'信息发送失败'];
    }

    /**
     * 工程师列表
     * @param Request $request
     * @return array
     */
    public function query(Request $request){
        $input = $request->param();
        $input['gid'] = 5;
        $input['apid'] = session('euid');
        if(empty($input['gid'])) return ['code'=>1,'msg'=>'gid参数错误'];
        $rows = db('admin')->alias('a')->where(function ($query)use($input){
            if(!empty($input['gid']))
                $query->where('a.group_id',$input['gid']);
            if(!empty($input['is_part']))
                $query->where('a.is_part',$input['is_part']);
            if(!empty($input['aid']))
                $query->where('a.admin_id',$input['aid']);
            if(!empty($input['apid']))
                $query->where('a.a_pid',$input['apid']);
            if(isset($input['is_at']))
                $query->where('a.is_at',$input['is_at']);
        })
            ->join('auth_group ag','a.group_id=ag.group_id','left')
            ->join('jobs js','js.id=a.jobs_id','left')
            ->field(['a.*,ag.title','js.title as jobs_title'])
            ->select();
        return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$rows,'rel'=>1];
    }

    /**
     * 创建团队
     * @param Request $request
     * @return array
     */
    public function team(Request $request){
        $did = $request->param('dis_id');
        $aids = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aids)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::team($did,$aids);
    }

    /**
     * 添加团队人员
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function addTeam(Request $request){
        $did = $request->param('dis_id');
        $aids = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aids)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::addTeam($did,$aids);
    }

    /**
     * 移除团队人员
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove(Request $request){
        $did = $request->param('dis_id');
        $aid = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::remove($did,$aid);
    }

    /**
     * 设置领队人
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function lead(Request $request){
        $did = $request->param('dis_id');
        $aid = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'did参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::lead($did,$aid);
    }

    /**
     * 任务团队
     * @param Request $request
     * @return array
     */
    public function teamList(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        $rows = db('dispatch_at')->alias('da')
            ->where('da.dispatch_id',$did)
            ->join('admin a','a.admin_id=da.admin_id','left')
            ->join('jobs j','j.id=a.jobs_id','left')
            ->field(['a.*','j.title as jobs_title','da.is_lead'])
            ->select();
        return ['code'=>1,'data'=>$rows];
    }

    /**
     * 跟踪列表
     * @param Request $request
     * @return array
     */
    public function track(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];

        $rows = db('dispatch_flow')->alias('df')
            ->order('df.id desc')
            ->where('df.dispatch_id',$did)
            ->join('admin a','a.admin_id=df.admin_id','left')
            ->field(['df.*','a.username'])
            ->select();
        return ['code'=>1,'data'=>$rows];
    }


    public function file(){
        $fileKey = array_keys(request()->file());
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($fileKey['0']);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['ext' => 'zip,rar,pdf,swf,ppt,psd,ttf,txt,xls,jpg,png'])->move('uploads');

        if($info){
            $result['code'] = 1;
            $result['info'] = '文件上传成功!';
            $path=str_replace('\\','/',$info->getSaveName());

            $result['url'] = '/uploads/'. $path;
            $result['ext'] = $info->getExtension();
            $result['size'] = byte_format($info->getSize(),2);
            return $result;
        }else{
            // 上传失败获取错误信息
            $result['code'] =0;
            $result['info'] = '文件上传失败!';
            $result['url'] = '';
            return $result;
        }
    }
}